package com.hustzp.com.xichuangzhu.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.hustzp.com.xichuangzhu.MainActivity;
import com.hustzp.com.xichuangzhu.R;
import com.hustzp.com.xichuangzhu.dao.LibraryDao;
import com.hustzp.com.xichuangzhu.dao.WorksDao;
import com.hustzp.com.xichuangzhu.model.Authors;
import com.hustzp.com.xichuangzhu.model.Library;
import com.hustzp.com.xichuangzhu.model.Review;
import com.hustzp.com.xichuangzhu.poetry.PoetryAuthorAct;
import com.hustzp.com.xichuangzhu.poetry.PoetryDetailAct;
import com.hustzp.com.xichuangzhu.poetry.adapter.WorksAdapter;
import com.hustzp.com.xichuangzhu.poetry.model.Works;
import com.hustzp.com.xichuangzhu.widget.ListViewIndex;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

/**
 * Copyright (C) 2015 The huimai mobile client Project
 * All right reserved.
 *
 * @author: wuzhimin@huimai365.com
 * @date: 2016/5/25 18:38
 * @Description:
 */
public class LibraryFragment extends Fragment implements RadioGroup.OnCheckedChangeListener, SearchView.OnCloseListener, SearchView.OnQueryTextListener {
    private ImageButton zuopingImg, exchangeImg;
    private List<Authors> authorses = new ArrayList<>();
    private HashMap<String, List<Authors>> authorHashMap = new HashMap<>();
    private List<Library> libraries = new ArrayList<>();
    private List<String> dyncList = new ArrayList<>();
    private List<Works> workses = new ArrayList<>();
    private WorksAdapter worksAdapter;
    private ListView worklistView;
    private ListViewIndex listViewIndex;

    RecyclerView recyclerView;
    HashMap<String, Integer> letters = new HashMap<>();
    private RelativeLayout productRay;
    private boolean click = false;
    private CityListWithHeadersAdapter headersAdapter;
    private RadioGroup radioGroup;
    private LinearLayout left_search_layout;
    private LinearLayout right_search_layout;
    private SearchView searchViewLeft;
    private SearchView searchViewRight;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_library, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        searchViewLeft = (SearchView) view.findViewById(R.id.searchViewLeft);
        searchViewRight = (SearchView) view.findViewById(R.id.searchViewRight);
        searchViewLeft.setOnCloseListener(this);
        searchViewRight.setOnCloseListener(this);
        searchViewLeft.setOnQueryTextListener(this);
        searchViewRight.setOnQueryTextListener(this);
//        searchView.onActionViewExpanded();
        radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(this);
        zuopingImg = (ImageButton) view.findViewById(R.id.zuiping_img);
        zuopingImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openMenu();
            }
        });
        exchangeImg = (ImageButton) view.findViewById(R.id.exchange_img);
        worklistView = (ListView) view.findViewById(R.id.work_list_view);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        listViewIndex = (ListViewIndex) view.findViewById(R.id.library_index);
        productRay = (RelativeLayout) view.findViewById(R.id.product_ray);
        left_search_layout = (LinearLayout) view.findViewById(R.id.left_search_layout);
        right_search_layout = (LinearLayout) view.findViewById(R.id.right_search_layout);
        productRay.setVisibility(View.GONE);
        zuopingImg.setVisibility(View.VISIBLE);
        exchangeImg.setVisibility(View.GONE);

        worklistView.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);

        //初始化作品列表
        worksAdapter = new WorksAdapter(getActivity(), workses);
        worklistView.setAdapter(worksAdapter);
        loadWorksData("");
        //设置列表数据和浮动header
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        // Add the sticky headers decoration
        headersAdapter = new CityListWithHeadersAdapter(authorses);
        recyclerView.setAdapter(headersAdapter);
        StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(headersAdapter);
        recyclerView.addItemDecoration(headersDecor);
        loadDefaultData();
        //切换
        exchangeImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (click) {//显示字母
                    headersAdapter.changeHeaderABC("", true);
                } else {//显示朝代
                    headersAdapter.changeHeaderDynasty("", true);
                }
                click = !click;
            }
        });

        worklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Works works = (Works) parent.getItemAtPosition(position);
                Intent intent = new Intent(getActivity(), PoetryDetailAct.class);
                intent.putExtra("from", LibraryFragment.class.getSimpleName());
                intent.putExtra(Works.class.getSimpleName(), works);
                startActivity(intent);

            }
        });
    }


    private void loadDefaultData() {
        //加载朝代信息
        LibraryDao dao = new LibraryDao(getActivity());
        libraries = dao.getDynasties();
        dyncList = new ArrayList<>();
        for (Library lib : libraries) {
            dyncList.add(lib.getName());
        }

        MyTask task1 = new MyTask(1, true);
        task1.execute("");

        MyTask task2 = new MyTask(2, false);
        task2.execute("");
    }

    private void loadWorksData(String search) {
        WorkTask task = new WorkTask(0);
        task.execute(search);
    }

    private void loadAuthorDynasty(String search, boolean refData) {
        MyTask task = new MyTask(2, refData);
        task.execute(search);
    }

    private void loadAuthorABC(String search, boolean refData) {
        MyTask task = new MyTask(1, refData);
        task.execute(search);
    }


    private void setListViewIndex(int headerType) {
        List<ListViewIndex.Index> indexMap = new ArrayList<>();
        String word = "";
        for (int i = 0; i < authorses.size(); i++) {
            Authors authors = authorses.get(i);
            String str;
            if (headerType == 1) {
                str = authors.getFirst_char();
            } else {
                str = authors.getDynasty().length() > 2 ? authors.getDynasty().substring(0, 2) : authors.getDynasty();
            }
            if (!word.equals(str)) {
                word = str;
                ListViewIndex.Index index = new ListViewIndex.Index(word, i);
                indexMap.add(index);
            }
        }

        listViewIndex.initIndexMap(indexMap);
        listViewIndex.setOnIndexTouchListener(new ListViewIndex.OnIndexTouchListener() {
            @Override
            public void onIndexTouched(String s) {
            }

            @Override
            public void onMappedPosition(int position) {
                recyclerView.scrollToPosition(position);
            }
        });

        if (headerType == 2) {
            listViewIndex.getLayoutParams().width = (int) (40 * getResources().getDisplayMetrics().density);
        } else {
            listViewIndex.getLayoutParams().width = (int) (30 * getResources().getDisplayMetrics().density);
        }

        listViewIndex.requestLayout();
    }

    /**
     * 隐藏软键盘
     */
    public void hideInput(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }


    @Override
    public boolean onClose() {
        switch (radioGroup.getCheckedRadioButtonId()) {
            case R.id.product_btn:
                hideInput(searchViewLeft);
                break;
            case R.id.library_btn:
                hideInput(searchViewRight);
                break;
        }
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        switch (radioGroup.getCheckedRadioButtonId()) {
            case R.id.product_btn:
                loadWorksData(newText);
                break;
            case R.id.library_btn:
                if (click) {
                    //显示朝代
                    headersAdapter.changeHeaderDynasty(newText, true);
                } else {
                    //显示字母
                    headersAdapter.changeHeaderABC(newText, true);
                }
                break;
        }
        return true;
    }


    class MyTask extends AsyncTask<String, Integer, List<Authors>> {
        private int taskID;
        private LibraryDao dao;
        private String key;
        private boolean refData;

        public MyTask(int taskID) {
            this.taskID = taskID;
            dao = new LibraryDao(getActivity());
        }

        public MyTask(int taskID, boolean refData) {
            this.taskID = taskID;
            this.refData = refData;
            dao = new LibraryDao(getActivity());
        }

        @Override
        protected List<Authors> doInBackground(String... params) {
            key = params[0];
            List<Authors> authorsList = null;
            switch (taskID) {
                case 1:
                    if (TextUtils.isEmpty(key)) {
                        authorsList = (List<Authors>) authorHashMap.get("abc");
                    }
                    if (authorsList == null) {
                        //按照字母加载作品家
                        authorsList = dao.getAuthorsOrderByABC(key);
                        for (Authors author : authorsList) {
                            Review review = dao.getQuotesByAuthor(author);
                            author.setQuotes(review);
                        }
                        if (TextUtils.isEmpty(key)) {
                            authorHashMap.put("abc", authorsList);
                        }
                    }
                    break;
                case 2:
                    if (TextUtils.isEmpty(key)) {
                        authorsList = (List<Authors>) authorHashMap.get("dynasty");
                    }
                    if (authorsList == null) {
                        //按照朝代加载作品家
                        authorsList = dao.getAuthorsOrderByDynasty(key);
                        for (Authors author : authorsList) {
                            Review review = dao.getQuotesByAuthor(author);
                            author.setQuotes(review);
                        }
                        //对列表进行排序
                        Collections.sort(authorsList, new Comparator() {
                            public int compare(Object a, Object b) {
                                Authors a1 = (Authors) a;
                                Authors b1 = (Authors) b;
                                int one = dyncList.indexOf(a1.getDynasty());
                                int two = dyncList.indexOf(b1.getDynasty());
                                return one - two;
                            }
                        });
                        if (TextUtils.isEmpty(key)) {
                            authorHashMap.put("dynasty", authorsList);
                        }
                    }
                    break;
            }
            return authorsList;
        }


        @Override
        protected void onPostExecute(List<Authors> authorsList) {
            switch (taskID) {
                case 1:
                    if (refData) {
                        authorses.clear();
                        authorses.addAll(authorsList);
                        headersAdapter.setKey(key);
                        headersAdapter.notifyDataSetChanged();
                        setListViewIndex(1);
                    }
                    break;
                case 2:
                    if (refData) {
                        authorses.clear();
                        authorses.addAll(authorsList);
                        headersAdapter.setKey(key);
                        headersAdapter.notifyDataSetChanged();
                        setListViewIndex(2);
                    }
                    break;
            }
        }


    }

    private void reSort() {
        //对作品重排序
        WorkTask task = new WorkTask(1);
        task.execute();
    }

    class WorkTask extends AsyncTask<String, Integer, List<Works>> {
        private int taskID;
        private WorksDao worksDao;
        private String search;

        public WorkTask(int taskID) {
            worksDao = new WorksDao(getActivity());
            this.taskID = taskID;
        }

        @Override
        protected List<Works> doInBackground(String... params) {
            switch (taskID) {
                case 0:
                    search = params[0];
                    List<Works> works = worksDao.getWorks(search);
                    return works;
                case 1:
                    worksDao.reSortWorks();
                    break;
            }
            return null;
        }


        @Override
        protected void onPostExecute(List<Works> authorsList) {
            switch (taskID) {
                case 0:
                    //加载作品列表
                    workses.clear();
                    workses.addAll(authorsList);
                    worksAdapter.setKey(search);
                    worksAdapter.notifyDataSetChanged();
                    break;
                case 1:
                    loadWorksData("");
                    break;
            }
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.product_btn:
                zuopingImg.setVisibility(View.VISIBLE);
                exchangeImg.setVisibility(View.GONE);
                worklistView.setVisibility(View.VISIBLE);
                productRay.setVisibility(View.GONE);
                recyclerView.setVisibility(View.GONE);
                left_search_layout.setVisibility(View.VISIBLE);
                right_search_layout.setVisibility(View.GONE);
                break;
            case R.id.library_btn:
                zuopingImg.setVisibility(View.GONE);
                exchangeImg.setVisibility(View.VISIBLE);
                worklistView.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
                productRay.setVisibility(View.VISIBLE);
                left_search_layout.setVisibility(View.GONE);
                right_search_layout.setVisibility(View.VISIBLE);
                //不自定义则默认26个字母
//                quickSideBarView.setLetters(customLetters);
//                adapter.addAll(authorses);
                break;
        }
    }

    private class CityListWithHeadersAdapter extends RecyclerView.Adapter<CityListWithHeadersAdapter.ViewHolder>
            implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder> {
        private List<Authors> authorList;

        private int headerType;
        private String key;

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public void changeHeaderABC(String search, boolean refData) {
            headerType = 1;
            loadAuthorABC(search, refData);
        }

        public void changeHeaderDynasty(String search, boolean refData) {
            headerType = 2;
            loadAuthorDynasty(search, refData);
        }

        public CityListWithHeadersAdapter(List<Authors> auList) {
            headerType = 1;
            authorList = auList;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.view_item, parent, false);
            ViewHolder vh = new ViewHolder(view);
            return vh;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.authorName.setText(authorses.get(position).getName());
            Review review = authorses.get(position).getQuotes();
            if (review != null) {
                holder.authorRemark.setText(review.getQuote());
            } else {
                holder.authorRemark.setText("");
            }
        }

        @Override
        public int getItemCount() {
            return authorList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            public TextView authorName;
            public TextView authorRemark;

            public ViewHolder(View view) {
                super(view);
                view.setOnClickListener(this);
                authorName = (TextView) view.findViewById(R.id.author_name);
                authorRemark = (TextView) view.findViewById(R.id.author_remark);
            }

            @Override
            public void onClick(View v) {
                Authors authors = authorses.get(getAdapterPosition());
                Works works = new Works();
                works.setAuthor_id(authors.getId());
                Intent intent = new Intent(getActivity(), PoetryAuthorAct.class);
                intent.putExtra(Works.class.getSimpleName(), works);
                startActivity(intent);
            }
        }

        @Override
        public long getHeaderId(int position) {
            if (headerType == 1) {
                return authorList.get(position).getFirst_char().hashCode();
            } else {
                return authorList.get(position).getDynasty().hashCode();
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.view_header, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position) {
            TextView textView = (TextView) holder.itemView;
            if (headerType == 1) {
                textView.setText(String.valueOf(authorList.get(position).getFirst_char()));
            } else {
                textView.setText(String.valueOf(authorList.get(position).getDynasty_tr()));
            }
        }

    }

    public void openMenu() {
        List<String> menus = new ArrayList<>();
        menus.add("重排序");
        final MainActivity activity = (MainActivity) getActivity();
        activity.initSharePopupWindow();
        activity.showSharePopupWindow(menus, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        activity.hideAlert();
                        reSort();
                        //重排序
                        break;
                }
            }
        });
    }
}
